package dalex.server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import dalex.world.World;

public class Server { 
	
	public Server() {
		/* 1.实例化serverSocket对象
		 * 2.一系列初始化操作
		 * 3.每accept一个socket，为其创建一个请求处理器（新线程），
		 */
		try{
			System.out.println("test") ; 
			Common.serverSocket = new ServerSocket(Common.SERVER_PORT) ; 	
		} catch (IOException ioe ){
			ioe.printStackTrace();
		}
		
		init() ;
		
		while(true){
			Socket socket = null; 
			try {
				socket = Common.serverSocket.accept() ;
				System.out.println("有客户端连接上...") ; 
				new Thread( new RequestProcessor(socket) ).start() ;
			} catch (IOException e) {
				e.printStackTrace();
			} 
		}
	}
	private void init() {  // initialization , 计数器置0 ， 加载地图资源与NPC资源 ， 创建数据库连接 。
		Common.onlinePlayerCounter = 0 ; 
		Common.onlineIOCacheCounter = 0 ; 
		loadMap() ; 
		connectDB() ; 
	}
	
	private void loadMap() {
		Common.world = World.createWorld();
	}

	private void connectDB() {
		try {
			Class.forName("com.mysql.jdbc.Driver") ;
			Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mud","root","");
			
			if(! conn.isClosed() )
			{
				System.out.println("Succeeded connecting to the Database!");
			}						
			
			Common.statement = conn.createStatement() ;
		}catch (Exception e ){
			e.printStackTrace();
		}
	}
	
	public static void main(String [] args){
		System.out.println("hello world ") ; 
		new Server() ;
	}
}
